package io.netty.protocodec;

import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;

/**
 * 客户端出站处理器
 *
 * @author Verlet
 * @date 2023-02-11 01:04
 */
@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("channelActive=====>");
        for (int i = 0; i < 10; i++) {
            MsgProto msgProto = new MsgProto();
            byte[] bytes = ("消息 " + i).getBytes(StandardCharsets.UTF_8);
            msgProto.setData(bytes);
            msgProto.setLength(bytes.length);
            ChannelFuture channelFuture = ctx.writeAndFlush(msgProto);
            int finalI = i;
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    log.info(finalI + "发送完了");
                }
            });

            Thread.sleep(1000);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("msg: " + msg.toString());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error(cause.getMessage());
    }
}
